//% color="#FF6347" iconWidth=45 iconHeight=45
namespace LLMAssistant {

    //% block="初始化模型 API地址[API_URL] API密钥[API_KEY] 模型[MODEL]" blockType="command"
    //% API_URL.shadow="string" API_URL.defl="https://api.deepseek.com"
    //% API_KEY.shadow="string" API_KEY.defl="api_key"
    //% MODEL.shadow="string" MODEL.defl="deepseek-chat"
    export function initializeLLM(parameter: any) {
        const apiUrl = parameter.API_URL.code;
        const apiKey = parameter.API_KEY.code;
        const model = parameter.MODEL.code;
		Generator.addInclude('HTTPClient', '#include <HTTPClient.h>');
		Generator.addInclude('ArduinoJson', '#include <ArduinoJson.h>');

		Generator.addObject(`model`, `String`,`model=${model};`);
		Generator.addObject(`api_key`, `String`,`api_key=${apiKey};`);
		Generator.addObject(`apiUrl`, `String`,`apiUrl=${apiUrl};`);
		Generator.addObject(`bot_prompt`,`String`,`bot_prompt="你是一个人工智能助手";`);
		Generator.addObject(`sendMessage`, 
		`String`,`sendMessage(String userMessage) {
			HTTPClient http;
			DynamicJsonBuffer jsonBuffer;
			
			http.begin(apiUrl+"/chat/completions");
			http.addHeader("Content-Type", "application/json");
			http.addHeader("Authorization", "Bearer " + api_key);
			
			JsonObject& root = jsonBuffer.createObject();
			root["model"] = model;
		
			JsonArray& messages = root.createNestedArray("messages");
		
			JsonObject& systemMessage = messages.createNestedObject();
			systemMessage["role"] = "system";
			systemMessage["content"] = bot_prompt+",回答简短";
		
			JsonObject& userMsg = messages.createNestedObject();
			userMsg["role"] = "user";
			userMsg["content"] = userMessage;
		
			String jsonString;
			root.printTo(jsonString);

			Serial.println(jsonString);


			http.POST(jsonString);
			String response = http.getString();
			while (response == "") {
				http.POST(jsonString);
				response = http.getString();
				delay(100);
			}


			Serial.println(response);
		
			JsonObject& responseRoot = jsonBuffer.parseObject(response);
			if (responseRoot.success()) {
				String ai_response=responseRoot["choices"][0]["message"]["content"];
				return ai_response;
			} else {
				return "";
			}
		}
`);
	}

	//% block="初始化提示词[bot_prompt]" blockType="command"
    //% bot_prompt.shadow="string" bot_prompt.defl="你是一个人工智能助手"
	export function prompt(parameter: any, block: any) {
        const bot_prompt = parameter.bot_prompt.code;
        Generator.addCode(`bot_prompt=${bot_prompt};`);
  }

    //% block="发送消息[MESSAGE] 并返回响应" blockType="reporter"
    //% MESSAGE.shadow="string" MESSAGE.defl="你好"
	export function sendMessage(parameter: any, block: any) {
        const message = parameter.MESSAGE.code;
        Generator.addCode(`sendMessage(${message})`);
  }
}
